package handler

import (
	"github.com/gin-gonic/gin"
	"monthtest5th/cache"
	"monthtest5th/model"
	"monthtest5th/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if password == "" || username == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号密码不可为空",
		})
		return
	}
	var user model.User
	redis_key := "user_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "该账户已被冻结",
		})
		return
	}
	if err := model.DB.Where("username = ?", username).Limit(1).Find(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户信息查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
func RoleAddPer(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	pid, _ := strconv.Atoi(c.PostForm("pid"))
	if rid == 0 || pid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "id不可为空",
		})
		return
	}
	data := model.RolePer{
		Rid: rid,
		Pid: pid,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色添加权限失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色权限添加成功",
	})
	return
}
func RoleDetail(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	if uid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "id不可为空",
		})
		return
	}
	var data model.Role
	if err := model.DB.Table("roles").
		Joins("left join user_roles on user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).
		Limit(1).
		Find(&data).
		Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
func PerDetail(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	if rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "id不可为空",
		})
		return
	}
	var data model.Per
	if err := model.DB.Table("pers").Joins("left join role_pers on role_pers.pid = pers.id").Where("role_pers.rid = ?", rid).Limit(1).Find(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
